package com.tony.mindhr.service;

import com.tony.mindhr.mapper.HrMapper;
import com.tony.mindhr.mapper.HrRoleMapper;
import com.tony.mindhr.model.Hr;
import com.tony.mindhr.utils.HrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: UserServie
 * @Auther: 皮蛋布丁
 * @Date: 2021/05/01/12:19
 * @Description:
 */
@Service
public class HrServie implements UserDetailsService {

    @Autowired
    HrMapper hrMapper;
    @Autowired
    HrRoleMapper hrRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Hr hr = hrMapper.loadUserByUsername(username);
        if(hr == null) {
            throw new UsernameNotFoundException("用户名 不存在！");
        }
        hr.setRoles(hrMapper.getRolesById(hr.getId()));

        return hr;
    }

    /**
    * @Description: getAllHrs 获取所有操作用户
    * @Param: []
    * @return: java.util.List<com.tony.mindhr.model.Hr>
    * @Author: 皮蛋布丁
    * @Date: 2021/6/6 22:25
     * @param keywords
    */
    public List<Hr> getAllHrs(String keywords) {
        return hrMapper.getAllHrs(HrUtils.getCurrentHr().getId(),keywords);
    }

    /**
    * @Description: updateHr 更新操作用户信息
    * @Param: [hr]
    * @return: java.lang.Integer
    * @Author: 皮蛋布丁
    * @Date: 2021/6/8 21:24
    */
    public Integer updateHr(Hr hr) {
        return hrMapper.updateByPrimaryKeySelective(hr);
    }

    /**
    * @Description: updateHrRoles 根据用户id更新用户
    * @Param: [hrid, rids]
    * @return: boolean
    * @Author: 皮蛋布丁
    * @Date: 2021/6/10 20:37
    */
    @Transactional
    public boolean updateHrRoles(Integer hrid, Integer[] rids) {
        //先删除表
        hrRoleMapper.deleteByHrid(hrid);
        //再添加
        return hrRoleMapper.addRole(hrid,rids) == rids.length;
    }

    /**
    * @Description: deletehrById 根据id删除hr
    * @Param: [id]
    * @return: java.lang.Integer
    * @Author: 皮蛋布丁
    * @Date: 2021/6/10 21:32
    */
    public Integer deletehrById(Integer id) {
        return hrMapper.deleteByPrimaryKey(id);
    }
}
